<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    

    <!-- 树形表格（使用v-if确保渲染时机） -->
    <el-table v-if="tableData.length > 0" :data="tableData"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" row-key="treeId" border
      style="width: 100%; margin-top: 10px;" v-loading="loading">
      <!-- 编号列 -->
      <el-table-column label="编号" align="center" width="180">
        <template slot-scope="scope">
          {{ scope.row.type === '厂房' ? scope.row.roomCode : scope.row.facilityCode }}
        </template>
      </el-table-column>

      <!-- 名称列 -->
      <el-table-column label="名称" align="center" width="180">
        <template slot-scope="scope">
          {{ scope.row.type === '厂房' ? scope.row.roomName : scope.row.facilityName }}
        </template>
      </el-table-column>

      <!-- 状态列 -->
      <el-table-column label="最新状态" align="center" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.type === '设备'">{{ scope.row.status }}</span>
        </template>
      </el-table-column>

      <!-- 评估内容列 -->

      <el-table-column label="当前评估内容" align="center">
        <template slot-scope="scope">
          <div v-html="scope.row.evaluationContent"></div>
        </template>
      </el-table-column>

      <!-- 巡检时间列 -->
      <el-table-column label="巡检时间" align="center" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.type === '设备'">{{ scope.row.inspectionTime }}</span>
        </template>
      </el-table-column>

      <!-- 巡检人员列 -->
      <el-table-column label="巡检人员" align="center" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.type === '设备'">{{ scope.row.inspector }}</span>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button v-if="scope.row.type === '设备'" type="text" size="small" @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button v-if="scope.row.type === '设备'" type="text" size="small" style="color: #f56c6c"
            @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 数据为空时显示 -->
    <div v-else-if="!loading" class="empty-state">
      暂无数据
    </div>

    <!-- 弹窗（使用v-if控制渲染） -->
    <el-dialog v-if="open" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="厂房ID" prop="roomCode">
          <el-input v-model="form.roomCode" placeholder="请输入厂房ID" disabled></el-input>
        </el-form-item>
        <el-form-item label="设备ID" prop="facilityCode">
          <el-input v-model="form.facilityCode" placeholder="请输入设备ID" disabled></el-input>
        </el-form-item>
        <el-form-item label="评估内容" prop="evaluationContent">
          
          <editor v-model="form.evaluationContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="form.status" placeholder="请输入状态" />
        </el-form-item>
        <el-form-item label="巡检时间" prop="inspectionTime">
          <el-date-picker v-model="form.inspectionTime" type="date" placeholder="请选择巡检时间" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="巡检人员" prop="inspector">
          <el-input v-model="form.inspector" placeholder="请输入巡检人员" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listEquipmentInspection,
  getEquipmentInspection,
  delEquipmentInspection,
  addEquipmentInspection,
  updateEquipmentInspection
} from "@/api/rooms/EquipmentInspection"

export default {
  name: "EquipmentInspection",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      tableData: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        inspector: null,
        createdAt: null,
      },
      form: {},
      rules: {}
    }
  },
  created() {
    // 延迟加载数据，确保组件初始化完成
    this.$nextTick(() => {
      this.getList()
    })
  },
  methods: {
    getList() {
      this.loading = true;
      listEquipmentInspection(this.queryParams).then(response => {
        const rows = response.rows || [];

        // 生成前端树形ID（treeId），保留设备的后端id
        const generateTreeId = (nodes, parentTreeId = '') => {
          nodes.forEach((node, index) => {
            // 1. 生成前端树形ID（仅用于表格row-key）
            node.treeId = `${parentTreeId}-${node.type}-${index}`;

            // 2. 处理children为null的情况
            node.children = node.children || [];

            // 3. 递归生成子节点treeId
            if (node.children.length > 0) {
              generateTreeId(node.children, node.treeId);
            }
          });
        };

        generateTreeId(rows);

        this.$nextTick(() => {
          this.tableData = rows;
          this.total = response.total;
          this.loading = false;
        });
      }).catch(error => {
        console.error("数据加载失败:", error);
        this.loading = false;
        this.tableData = [];
      });
    },

    cancel() {
      this.open = false
      // 安全重置表单
      this.$nextTick(() => {
        this.reset()
      })
    },

    reset() {
      this.form = {
        id: null,
        roomCode: null,
        facilityCode: null,
        evaluationContent: null,
        status: null,
        inspectionTime: null,
        inspector: null,
        createdAt: null
      }
      // 检查表单引用是否存在
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },

    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 100,
        inspector: null,
        createdAt: null,
      }
      this.handleQuery()
    },

    handleSelectionChange(selection) {
      const devices = selection.filter(item => item.type === '设备')
      this.ids = devices.map(item => item.id)
      this.single = devices.length !== 1
      this.multiple = !devices.length
    },

    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加设备巡检记录"
    },

    handleUpdate(row) {
      if (row.type !== '设备') {
        this.$message.warning("仅设备可修改");
        return;
      }

      // 设备节点的后端业务ID（如1968149796972515329）
      const equipmentBusinessId = row.id;
      if (!equipmentBusinessId) {
        this.$message.error("未获取到设备记录ID，无法修改");
        return;
      }

      this.reset(); // 重置表单
      getEquipmentInspection(equipmentBusinessId).then(response => {
        const equipmentData = response.data || {};
        this.form = {
          id: equipmentData.id || '', // 后端业务ID（更新时传递）
          roomCode: equipmentData.roomCode || '',
          facilityCode: equipmentData.facilityCode || '',
          evaluationContent: equipmentData.evaluationContent || '',
          status: equipmentData.status || '',
          inspectionTime: equipmentData.inspectionTime || '',
          inspector: equipmentData.inspector || '',
          createdAt: equipmentData.createdAt || ''
        };
        this.open = true;
        this.title = "修改设备巡检记录";
      }).catch(error => {
        console.error("获取设备详情失败:", error);
        this.$message.error("获取数据失败，请重试");
      });
    },

    submitForm() {
      if (!this.$refs.form) return;

      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true;
          const submitData = {
            id: this.form.id, // 设备后端业务ID（必传）
            roomCode: this.form.roomCode,
            facilityCode: this.form.facilityCode,
            evaluationContent: this.form.evaluationContent,
            status: this.form.status,
            inspectionTime: this.form.inspectionTime,
            inspector: this.form.inspector
          };
          updateEquipmentInspection(submitData).then(response => {
            if (response.code === 200) {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            } else {
              this.$message.error(`修改失败：${response.msg || '未知错误'}`);
            }
          }).catch(error => {
            console.error("更新设备失败:", error);
            this.$message.error("服务器异常，请稍后重试");
          }).finally(() => {
            this.loading = false;
          });
        }
      });
    },

    handleDelete(row) {
      if (row.type !== '设备') {
        this.$message.warning("仅设备可删除");
        return;
      }

      const equipmentBusinessId = row.id; // 设备后端业务ID
      if (!equipmentBusinessId) {
        this.$message.error("未获取到设备记录ID，无法删除");
        return;
      }

      this.$confirm(`是否确认删除设备巡检记录（ID：${equipmentBusinessId}）？`).then(() => {
        delEquipmentInspection(equipmentBusinessId).then(() => {
          this.$message.success("删除成功");
          this.getList(); // 重新加载列表
        }).catch(error => {
          console.error("删除设备失败:", error);
          this.$message.error("删除失败，请重试");
        });
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },
    handleExport() {
      this.download('rooms/EquipmentInspection/export', {
        ...this.queryParams
      }, `EquipmentInspection_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.empty-state {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>
